package com.cntv.androidviewmmodel;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.lifecycle.SavedStateHandle;

import com.cntv.viewmodeldemo.R;

/**
 * Created By Mahongyin
 * Date    2020/9/17 10:58
 * AndroidViewModel是ViewModel的一个子类，可以直接调用getApplication()，由此可以访问应用的全局资源
 * ViewModel 的SavedStateHandle
 */
public class MyAndroidViewModel extends AndroidViewModel implements LifecycleObserver {
    SavedStateHandle handle;
    String key = getApplication().getResources().getString(R.string.sp_key);
    String spName = getApplication().getResources().getString(R.string.sp_name);

    public MyAndroidViewModel(@NonNull Application application, SavedStateHandle savedStateHandle) {
        super(application);
        this.handle = savedStateHandle;
        if (!handle.contains(key)){
            load();
        }
    }

    public LiveData<Integer> getNum() {
        return handle.getLiveData(key);
    }

    void load() {
        SharedPreferences sp = getApplication().getSharedPreferences(spName, Context.MODE_PRIVATE);
        int value = sp.getInt(key, 0);
        handle.set(key, value);
    }

   void save() {
        SharedPreferences sp = getApplication().getSharedPreferences(spName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(key, getNum().getValue());
        editor.apply();
    }

   public void add(int n) {
        handle.set(key, getNum().getValue() + n);
//        save();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    private void actPause(){
        save();
    }
}
